<?php

namespace Frieza\Modules\BusinessTool\Controllers;

use App\Exceptions\InputErrorException;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\tools\Checker;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Doraemon\model\CommentBeautifyManagement;
use Doraemon\model\CommentBeautifyFill;

class CommentController
{
    public function index(Content $content, Request $request)
    {
        $objId = $request->input('obj_id');
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 15);
        $limit = [($page - 1) * $pageSize, $pageSize];
        $where = ['c_b_status' => CommentBeautifyManagement::STATUS_NORMAL];
        if ($objId) {
            $where['obj_id'] = $objId;
        }
        $list = CommentBeautifyManagement::getList($where, $limit);
        $total = CommentBeautifyManagement::getTotal($where);

        $gridModel = new pGridDataModel($list, $total);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->expandFilter();
            $grid->disableRowSelector();

            $grid->filter(function (Grid\Filter $filter){
                $filter->disableIdFilter();
                $filter->column(1 / 2, function (Grid\Filter $filter) {
                    $filter->equal('obj_id', '内容id');
                });
            });

            $grid->hideColumns('id');
            $grid->column('obj_id', '内容id');
            $grid->column('content', '评论信息')->display(function () {
                return nl2br($this->content);
            });
            $grid->column('start_time', '开始时间')->display(function () {
                return date('Y-m-d H:i:s', $this->start_time);
            });

            $grid->column('end_time', '结束时间')->display(function () {
                return date('Y-m-d H:i:s', $this->end_time);
            });
            $grid->column('addtime', '创建时间')->display(function () {
                return date('Y-m-d H:i:s', $this->addtime);
            });
            $grid->column('admin_id', '创建人')->display(function () {
                if ($this->addtime > strtotime('2022-07-23')) {
                    return Admin::user()->find($this->admin_id)->name;
                }
                return '-';
            });
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableEdit();
            });
        });

        return $content
            ->header('评论美化')
            ->body($listGrid);
    }

    public function create(Content $content)
    {
        $form = new Form([]);
        $form->text('obj_id',' 内容id')->required();
        $form->textarea('content', '评论内容')->required();
        $form->dateTimeRange('start_time', 'end_time', '美化时间')->required();
        $form->action('/admin/BusinessTool/comment/index/save');
        return $content
            ->header('数据美化配置')
            ->breadcrumb(['text' => '数据美化列表', 'url' => '/BusinessTool/comment/index'], ['text' => '数据美化配置'])
            ->row($form);
    }

    public function save(Request $request)
    {
        $objId = $request->input('obj_id');
        if (!Checker::isObjid($objId)){
            throw new InputErrorException('请正确填写内容id', InputErrorException::DEFAULT_CODE, 'obj_id');
        }

        $content = $request->input('content');
        $commentList = explode("\n", trim($content));
        $startTime = strtotime($request->input('start_time'));

        if ($startTime < time()) {
            throw new InputErrorException('开始时间必须大于当前时间', InputErrorException::DEFAULT_CODE, 'start_time');
        }

        $endTime = strtotime($request->input('end_time'));

        $data = [
            'obj_id' => $objId,
            'content' => $content,
            'start_time' => $startTime,
            'end_time' => $endTime,
            'admin_id' => Admin::user()->id,
            'addtime' => time()
        ];

        $beautifyId = CommentBeautifyManagement::add($data);
        $commentInterval = ($endTime - $startTime) / count($commentList);
        foreach ($commentList as $i => $commentContent){
            $beautifyFillInfo = [];
            $beautifyFillInfo['beautify_id'] = $beautifyId;
            $beautifyFillInfo['obj_id'] = $objId;
            $beautifyFillInfo['content'] = $commentContent;
            $beautifyFillInfo['beautify_time'] = $startTime + ($i * $commentInterval) + rand(0, $commentInterval);
            $beautifyFillInfo['beautify_status'] = CommentBeautifyFill::STATUS_WAIT;
            $beautifyFillInfo['addtime'] = time();
            CommentBeautifyFill::insertData($beautifyFillInfo);
        }

        return redirect(url("/admin/BusinessTool/comment/index"));
    }

    public function delete($id)
    {
        CommentBeautifyManagement::deleteById($id); // 删除主表记录
        CommentBeautifyFill::deleteByBeautifyId($id); // 删除从表记录
        return response()->json([
        'status' => true,
        'then' => [
            'action' => 'refresh',
            'value'  => true,
        ],
        'toastr' => [
            'type' => 'success',
            'content' => '删除成功',
            'options' => [
                'positionClass' => 'toast-top-center'
            ]
        ]
    ]);
    }
}